package com.crl.module.npc.controller
{
	import com.crl.module.npc.model.Section;
	import com.crl.module.npc.model.action.IAction;
	import com.crl.module.npc.model.action.QueueAction;
	import com.crl.module.npc.view.AbstractNpcView;
	import com.crl.module.npc.view.INpcView;
	import com.crl.utils.HashMap;

	public class AbstractNpcLogic implements INpcLogic
	{
		protected var sections:HashMap;
		private var actions:HashMap;
		
		public function AbstractNpcLogic()
		{
			sections=new HashMap();
			actions=new HashMap();
		}
		
		private function getViewer():INpcView{
			//sub class todo override it;
			return new AbstractNpcView();
		}
		
		public function addAction(action:IAction):void{
			this.actions.put(action.getType(),action);
		}
		
		public function gotoSection(key:String):void
		{
			var section:Section=sections.getValue(key);
			if(section==null){
				return;
			}
			
			if(section.getAction()){
				
				section.getAction().execute();
				
			}else{
				
				getViewer().fillSection(section);
			
			}
		}
		
		public function parseSections(xml:XML):void
		{
			sections.clear();
			
			var list:XMLList=xml.descendants("section");
			
			var key:String;
			var actionXML:XML;
			var words:String;
			var items:Array;
			
			var section:Section;
			var action:IAction;
			for each(var item:XML in list){
				
				
				action=null;
				words=null;
				items=null;
				
				
				key=item.@key;
				
				actionXML=item.children()[0];
				if(actionXML.localName() != "item"){
					action=parseAction(actionXML);
				}else{
					words=item.@word;
					items=this.createItems(item.item);
				}
				
				if(words==null){
					words="";
				}
				
				section=new Section(words,items,action);
				
				sections.put(key,section);
			}
			
		}
		
		private function parseAction(xml:XML):IAction{
			var commandName:String=xml.localName().toString();
			
			var action:IAction=actions.getValue(commandName);
			if(action){
				action=action.clone();
				action.parseXML(xml);
				return action;
			}else{
				return new NoAction();
			}
		}
		
		
		private function createItems(list:XMLList):Array{
			var arr:Array=[];
			if(list==null){
				return arr;
			}
			
			for each(var item:XML in list){
				arr.push(this.createItem(item));
			}
			return arr;
		}
		
		private function createItem(xml:XML):Item{
			var list:XMLList=xml.children();
			
			var action:IAction;
			if(list.length()>1){
				var queueAction:QueueAction=new QueueAction();
				for each(var item:XML in list){
					queueAction.push(parseAction(item));
				}
				
				action=queueAction;
			}else{
				action=parseAction(list[0]);
			}
			var lable:String=xml.@word;
			return new Item(lable,action);
		}
		
		
		public function start():void
		{
			this.gotoSection("begin");
		}
		
		public function exit():void
		{
			this.getViewer().dispose();
		}
	}
}